const express = require('express');

const router = express.Router();

const session = require('express-session');

const articleModel = require('../model/articleModel');

//渲染index
router.get('/', (req, res) => {
    articleModel.find().populate('user', 'username avatar').exec((err, articles) => {
        res.render('index', {
            articles
        });
    });
});

//渲染写文章页面
router.get('/send', (req, res) => {
    res.render('send');
});
router.post('/addArticle', (req, res) => {

    let article = new articleModel({
        user: req.body.userId,
        title: req.body.title,
        content: req.body.content
    });
    if (article) {
        article.save((err, info) => {
            if (err) {
                res.send('发表失败')
            } else {
                res.redirect('/article/')
            }
        });
    } else {
        return res.send("文章不能为空~")
    }

});

//点赞文章
router.post('/likeArticle/:articleId', (err, res) => {
    
});


//删除文章
router.get('/deleteArticle/:articleId', (req, res) => {
    let articleId = req.params.articleId;
    console.log('articleId', articleId);

    articleModel.remove({
        _id: articleId
    }, (err, articles) => {
        if (err) {
            console.log(err);
        } else {
            console.log('删除成功');
            console.log(articles);
            res.redirect('/article/');
        }
    });
});

module.exports = router;